package com.richrail.console;

import java.util.LinkedHashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.richrail.model.entities.DepotStorage;

public class CLI
{
	final static Logger logger = LoggerFactory.getLogger(CLI.class);
	
	// They must be unique and sorted, because it makes no sense to notify the same object twice.
	private Set<ResponseListener> listeners = new LinkedHashSet<ResponseListener>();
	
	private Executor executor;
	
	public CLI(DepotStorage depotStorage)
	{
		executor = new JavaExecutor(depotStorage);
	}
	
	public CLI(Executor executor)
	{
		this.executor = executor;
	}
	
	public String execute(String input)
	{
		String response = executor.execute(input);
		fireResponseListeners(response);
		logger.info(response);
		
		return null;
	}
	
	public void addResponseListener(ResponseListener listener)
	{
		listeners.add(listener);
	}

	public void removeResponseListener(ResponseListener listener)
	{
		listeners.remove(listener);
	}
	
	// We just want a callback, so we won't use an EventObject,
	// since that gives unnecessary high coupling through getSource.
	public void fireResponseListeners(String response)
	{
		for (ResponseListener listener: listeners)
		{
			listener.onResponse(response);
		}
	}

	public static void main(String[] args)
	{
		// Could be implemented, but is not really necessary for the current use case
		// where the only interaction with the CLI is through the console display.
		
		// For now the main method is only used to test the commands.
		JavaExecutor.testCommands();
	}
}
